import Validate from './validate.js';
import regeneratorRuntime from '../libs/wxPromise.min';

import siteInfo from '../siteinfo.js';
const prefix = siteInfo.prefix
const prefixString = siteInfo.prefixString
const imageUrl = siteInfo.siteroot

export default {
  //验证
  Validate,
  regeneratorRuntime,
  // 基础url
  imageUrl,
  //动态设置头部title
  setNavTitle(val) {
    prefix.setNavigationBarTitle({
      title: val
    })
  },
  //动态设置头部颜色
  setNavColor(val) {
    prefix.setNavigationBarColor({
      frontColor: '#ffffff', //前景颜色值，包括按钮、标题、状态栏的颜色，仅支持 #ffffff 和 #000000
      backgroundColor: '#ff0000', //背景颜色值
      animation: {
        duration: 400,
        timingFunc: 'linear'
      }
    })
  },
  //返回类型
  typeOf(param) {
    return Object.prototype.toString.call(param).slice(8, -1)
  },
  //判断对象所有属性值中某一个为空
  objectEmpty(param) {
    return new Promise((resove, reject) => {
      for (let key in param) {
        if (param[key] == '') {
          resove(key)
        }
      }
    })
  },
  //弹出框,返回状态
  showModalContent(param = '提示', confirmText = '同意', show = true, cancelText = '取消', ) {
    return new Promise((resove, reject) => {
      prefix.showModal({
        content: param,
        showCancel: show,
        cancelText: cancelText,
        confirmText: confirmText,
        success: function(res) {
          if (res.confirm) {
            resove(true)
          }
        },
        complete: function(res) {

        },
        fail() {
          resove(false)
        },
      })
    })
  },
  //判断是否为空
  isEmpty(param) {
    //基本类型为空
    let condition1 = param === '' || param === null || param === undefined || param === "NaN";

    let condition2;
    let condition3

    //引用类型为空
    if (!condition1) {
      condition2 = this.typeOf(param) === "Object" && Object.keys(param).length < 1;
      condition3 = this.typeOf(param) === "Array" && param.length < 1;
    }
    return condition1 || condition2 || condition3;
  },
  //检查授权
  checkAuth(name) {
    let that = this;
    return new Promise((resove, reject) => {
      prefix.getSetting({
        success(res) {
          if (res.authSetting[`scope.${name}`]) {
            resove(true)
          } else {
            resove(false)
          }
        },
        fail() {
          that.networkError()
        }
      })
    })
  },
  //主动授权
  authorize(name) {
    // console.log(name)
    let that = this;
    return new Promise((resove, reject) => {
      prefix.authorize({
        scope: `scope.${name}`,
        success(res) {
          resove(res)
        },
        fail() {
          that.authFail()
        },
      })
    })
  },
  //小程序自带搜索获取地址及经纬度
  chooseLocation() {
    let that = this;
    return new Promise((resove, reject) => {
      prefix.chooseLocation({
        success: function(res) {
          resove(res)
        },
        fail: function(res) {
          // console.log(res)
          that.hideAll()
          let errMsg = res.errMsg;
          if (errMsg.indexOf('auth') > -1) that.authFail("地理位置")
        }
      })
    })
  },
  //小程序自带获取定位
  getLocation() {
    let that = this;
    return new Promise((resove, reject) => {
      prefix.getLocation({
        success: function(res) {
          resove(res)
        },
        fail: function(res) {
          // console.log(res)
          that.hideAll()
          let errMsg = res.errMsg;
          if (errMsg.indexOf('auth') > -1) that.authFail("地理位置")
        }
      })
    })
  },
  //百度地图获取定位
  getBmapLocation: function() {
    //定位
    this.showLoading('定位中,请稍等')
    let that = this;
    let bmap = require('./bmap-prefix.min.js');
    let BMap = new bmap.BMapWX({
      ak: 'GoI7BxLpfvBEyf1TcMXCloi99Vov7flZ'
    });
    return new Promise((resolve, reject) => {
      BMap.regeocoding({
        success: function(data) {
          let addressInfo = data.originalData.result;
          let {
            lat: latitude,
            lng: longitude
          } = addressInfo.location;
          let {
            formatted_address
          } = addressInfo;
          //只返回需要的数据
          let locationInfo = {
            name: formatted_address,
            latitude,
            longitude,
            address: formatted_address,
            city: addressInfo.addressComponent.city
          }
          //成功回调
          resolve(locationInfo)
        },
        fail: function(res) {
          console.log(res)
          that.hideAll()
          //失败回调
          let errMsg = res.errMsg;
          if (errMsg.indexOf('auth') > -1) that.authFail("地理位置")
        },
        complete() {
          that.hideAll()
        },
      })
    })
  },
  //授权失败提示 openSetting
  authFail(msg = "需要的") {
    //是否有设置页面,有提示跳转设置页面,没有则提示用小程序自带的
    let haveSetupPage = true;
    if (haveSetupPage) {
      prefix.showModal({
        title: '未授权',
        content: `为保证功能正常使用,需打开${msg}权限，去开启?`,
        showCancel: true,
        success: function(res) {
          if (res.confirm) {
            prefix.navigateTo({
              url: '/pages/login/index?openType=openSetting',
            })
          }
        }
      })
      return;
    }
    prefix.showModal({
      title: '未授权',
      content: `为保证功能正常使用,点击「右上角」-「关于**」-「右上角」-「设置」,打开${msg}权限后重试`,
      showCancel: false,
    })

  },
  //生成从minNum到maxNum的随机数
  randomNum(minNum, maxNum) {
    switch (arguments.length) {
      case 1:
        return parseInt(Math.random() * minNum + 1, 10);
        break;
      case 2:
        return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
        break;
      default:
        return 0;
        break;
    }
  },
  //网络错误提示
  networkError(msg = "服务器开小差了,请稍后再试", status = 0) {
    let titleObj = {
      250: "code错误",
      1: "请求超时",
      500: "服务器错误",
      404: "404"
    }
    let title = titleObj[status] || "网络错误"
    this.hideAll();
    this.showModal(title)
    // if (this.getPage().onPullDownRefresh) {
    //   prefix.showModal({
    //     title,
    //     content: `${msg}`,
    //     showCancel: false,
    //     // confirmText: '关闭窗口',
    //     // cancelText: '等会刷新',
    //     success(res) {
    //       if (res.confirm) {
    //         // prefix.startPullDownRefresh()
    //       }
    //     }
    //   })
    // } else {
    //   this.showToast(msg,'none')
    // }
  },
  /* 打开提示信息 */
  showModal(content = "服务器错误") {
    prefix.showModal({
      title: "提示",
      content,
      showCancel: false
    })
  },
  showLoading(title = "加载中") {
    prefix.showLoading({
      title,
      mask: true
    })
  },
  showToast(title = "操作成功", icon = 'success') {
    prefix.showToast({
      title,
      icon
    })
  },
  getStorageSync(key = ''){
    return prefix.getStorageSync(key)
  },
  setStorage({key,data,success}){
    prefix.setStorage({
      key:key,
      data:data,
      success:()=>{
        success && success()
      }
    })
  },
  navigateBack(){
    prefix.navigateBack({
      delta: 1
    })
  },
  chooseImage({count=0,sizeType=[],sourceType=[],success}){
    prefix.chooseImage({
      count: count,
      sizeType: sizeType,
      sourceType: sourceType,
      success: (result)=>{
        success && success(result)
      },
      fail: ()=>{},
      complete: ()=>{}
    });
  },
  /* 隐藏所有提示信息 */
  hideAll() {
    prefix.hideLoading();
    prefix.stopPullDownRefresh();
    prefix.hideNavigationBarLoading();
  },
  //跳转
  goUrl(url, method = 'navigateTo') {
    console.log(url, method)
    if (!url) {
      return;
    }
    //拨打电话
    if (url.indexOf('tel:') > -1) {
      prefix.makePhoneCall({
        phoneNumber: url.split(':')[1],
      })
      return;
    }
    //网页跳转
    if (url.indexOf('http') > -1) {
      prefix.navigateTo({
        url: `/pages/webview/Index?url=${url}`,
      })
      return;
    }
    //小程序跳转
    if (url.indexOf('wx') == 0) {
      var appIdData, pathData = '',
        envVersionData = 'release';

      var urlArr = url.split(':');
      if (urlArr.length == 1) {
        appIdData = urlArr[0];
      } else if (urlArr.length == 2) {
        appIdData = urlArr[0];
        pathData = urlArr[1];
      } else if (urlArr.length == 3) {
        appIdData = urlArr[0];
        pathData = urlArr[1];
        envVersionData = urlArr[2];
      }

      prefix.navigateToMiniProgram({
        appId: appIdData,
        path: pathData,
        extraData: {
          lb: 'longbing'
        },
        envVersion: envVersionData,
        success(res) {
          // 打开成功
        }
      })
      return;
    }

    //正常页面跳转
    let urls = url.split('://')
    if (urls.length > 1) {
      url = urls[1]
      method = urls[0];
    }
    wx[method]({
      url
    })

  },
  navigateToMiniProgram({appId='',path='',envVersionData=''}){
    prefix.navigateToMiniProgram({
      appId: appId,
      path: path,
      extraData: {
        lb: 'longbing'
      },
      envVersion:envVersionData ,
      success(res) {
        // 打开成功
      }
    })
  },
  
  //获取标签上data
  getDataSet(e) {
    return e.currentTarget.dataset
  },
  //获表单控件值
  getValue(e) {
    return e.detail.value
  },
  //加密 主要针对跳转web-view 传递数据
  setOptions(o) {
    return encodeURIComponent(JSON.stringify(o))
  },
  //解密
  getOptions(o) {
    return JSON.parse(decodeURIComponent(o))
  },
  //获取页面对象，0时为当前页面
  getPage(index = 0) {
    let pages = getCurrentPages();
    let page = pages[pages.length - 1 + index]
    return page
  },
  //发起支付
  pay(orderInfo) {
    let that = this;

    let PayInfo

    if (prefixString == 'wx') {
      PayInfo = {
        timeStamp: orderInfo.timeStamp,
        nonceStr: orderInfo.nonceStr,
        'package': orderInfo.package,
        signType: orderInfo.signType,
        paySign: orderInfo.paySign,
      }
    } else {
      PayInfo = {
        package: `prepay_id=${orderInfo}`,
        bargainor_id: "1543333871", //商户号
      }
    }

    return new Promise((resolve, reject) => {
      prefix.requestPayment(
        {
          ...PayInfo,
          success: function (res) {
            resolve(true)
          },
          fail: function (res) {
            console.log(res)
            resolve(false)
          }
        }
      )
    })
  },

  //格式化时间
  formatTime(date, format) {
    let newFormat = format || 'YY-M-D h:m:s';
    let formatNumber = this.formatNumber;
    let newDate
    if (typeof date == 'object') {
      newDate = date
    }
    if (Object.prototype.toString.call(newDate).slice(8, -1) !== "Date") {
      newDate = new Date(date * 1000);
    }
    let week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', '日', '一', '二', '三', '四', '五', '六'];
    return newFormat.replace(/YY|Y|M|D|h|m|s|week|星期|周/g, function(a) {
      switch (a) {
        case 'YY':
          return newDate.getFullYear();
        case 'Y':
          return (newDate.getFullYear() + '').slice(2);
        case 'M':
          return formatNumber(newDate.getMonth() + 1);
        case 'D':
          return formatNumber(newDate.getDate()) > 0 ? formatNumber(newDate.getDate()) : '';
        case 'h':
          return formatNumber(newDate.getHours());
        case 'm':
          return formatNumber(newDate.getMinutes());
        case 's':
          return formatNumber(newDate.getSeconds());
        case '星期':
          return "星期" + week[newDate.getDay() + 7];
        case '周':
          return "周" + week[newDate.getDay() + 7];
        case 'week':
          return week[newDate.getDay()];
      }
    })
  },
  //格式化数字
  formatNumber(n) {
    n = n.toString();
    return n[1] ? n : '0' + n
  },
  reLaunch({url='',success=()=>{}}){
    prefix.reLaunch({
      url: url,
      success: (result)=>{
        success && success(result)
      },
      fail: ()=>{},
      complete: ()=>{}
    });
  },
  
  /**
   * 时间 多久之前
   */
  ctDate(date) {
    const minute = 1000 * 60;
    const hour = minute * 60;
    const day = hour * 24;
    const month = day * 30;


    if (!date) return "";
    const now = Date.now();
    let diffValue;
    let result;
    date = typeof date === "number" ? date : +(new Date(date));
    diffValue = now - date;

    let monthC = diffValue / month;
    let weekC = diffValue / (7 * day);
    let dayC = diffValue / day;
    let hourC = diffValue / hour;
    let minC = diffValue / minute;

    if (monthC >= 1) {
      result = parseInt(monthC) + "月前";
    } else if (weekC >= 1) {
      result = parseInt(weekC) + "星期前";
    } else if (dayC >= 1) {
      result = parseInt(dayC) + "天前";
    } else if (hourC >= 1) {
      result = parseInt(hourC) + "小时前";
    } else if (minC >= 1) {
      result = parseInt(minC) + "分钟前";
    } else {
      result = "刚刚";
    }

    return result;
  },
  /*
   * 获取链接某个参数
   * url 链接地址
   * name 参数名称
   */
  getUrlParam: function(url, name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象  
    var r = url.split('?')[1].match(reg); //匹配目标参数  
    if (r != null) return unescape(r[2]);
    return null; //返回参数值  
  },
  //将一个数组根据规则分为两个
  partition: function(arr, isValid) {
    arr.reduce(
      ([pass, fail], elem) =>
      isValid(elem) ? [
        [...pass, elem], fail
      ] : [pass, [...fail, elem]], [
        [],
        []
      ],
    )
  },
  //将一个数组分为多个数组
  group(array, subGroupLength) {
    let index = 0;
    let newArray = [];
    while (index < array.length) {
      newArray.push(array.slice(index, index += subGroupLength));
    }
    return newArray;
  },
  //深拷贝
  deepCopy(o) {
    let that = this;
    if (o instanceof Array) {
      var n = [];
      for (var i = 0; i < o.length; ++i) {
        n[i] = that.deepCopy(o[i]);
      }
      return n;
    } else if (o instanceof Function) {
      var n = new Function("return " + o.toString())();
      return n;
    } else if (o instanceof Object) {
      var n = {};
      for (var i in o) {
        n[i] = that.deepCopy(o[i]);
      }
      return n;
    } else {
      return o;
    }
  },
  //查询某个字符在字符串的位置
  searchSubStr: function(str, subStr) {
    let positions = [];
    let pos = str.indexOf(subStr);
    while (pos > -1) {
      positions.push(pos);
      pos = str.indexOf(subStr, pos + 1);
    }
    return positions
  },
  //数组累加
  reduceNum(arr) {
    return arr.reduce((previousValue, currentValue) => {
      return previousValue + currentValue
    })
  },
  //返回第一个符合条件的索引号
  findIndex(arr, fn) {
    return arr.findIndex(val => {
      return fn(val)
    })
  },
  //返回第一个符合条件的对象
  find(arr, fn) {
    return arr.find(val => {
      return fn(val)
    })
  },
  //判断数组中是否拥有满足条件的内容 返回true false
  find(arr, fn) {
    return arr.find(val => {
      return fn(val)
    })
  },
  //判断数组是否全部满足某个条件
  every(arr, fn) {
    return arr.every(val => {
      return fn(val)
    })
  },
  //找到符合条件的对象 当找到后 不会继续执行
  some(arr, fn) {
    return arr.some(val => {
      return fn(val)
    })
  },
  //返回数组 其中是符合条件的对对象
  filter(arr, fn) {
    return arr.filter(val => {
      return fn(val)
    })
  },
  //返回一个被修改后数组
  map(arr, fn) {
    return arr.map(val => {
      return fn(val)
    })
  },
  throttle(fn, gapTime) {
    if (gapTime == null || gapTime == undefined) {
      gapTime = 1500
    }

    let _lastTime = null
    return function() {
      let _nowTime = +new Date()
      if (_nowTime - _lastTime > gapTime || !_lastTime) {
        fn()
        _lastTime = _nowTime
      }
    }
  },
  /**
   * @desc 函数防抖
   * @param func 函数
   * @param wait 延迟执行毫秒数
   * @param immediate true 表立即执行，false 表非立即执行
   */
  debounce(func, wait, immediate) {
    var timeout = null;
    return function() {
      var context = this;
      var args = arguments;

      if (timeout) clearTimeout(timeout);
      if (immediate) {
        let callNow = !timeout;
        timeout = setTimeout(function() {
          timeout = null;
        }, wait)
        if (callNow) func.apply(context, args)
      } else {
        timeout = setTimeout(function() {
          func.apply(context, args)
        }, wait);
      }
    }
  },
}